import {Component, Input, OnInit} from '@angular/core';
import {FetchService} from '../../../../core/net/fetch.service';
import {OneMapService} from '../../../one-map/one-map.service';
import {FormBuilder, FormGroup} from '@angular/forms';
import {NzMessageService, NzTreeNode} from 'ng-zorro-antd';
import {MenuItemModel} from '../../../../core/auth/auth.service';
import {format, startOfMonth, endOfMonth} from 'date-fns';
import {HttpClient, HttpHeaders} from "@angular/common/http";

@Component({
  selector: 'app-ecologic-water-single',
  templateUrl: './ecologic-water-single.component.html',
  styleUrls: ['./ecologic-water-single.component.scss', '../ecologic-water.component.scss']
})
export class EcologicWaterSingleComponent implements OnInit {
  // tslint:disable-next-line:variable-name
  _dateRangeVal = [startOfMonth(new Date()), endOfMonth(new Date())];
  @Input()
  get dateRangeVal() {
    return this._dateRangeVal;
  }

  set dateRangeVal(val) {
    this._dateRangeVal = val;
    this.queryInfo();
  }

  baseUrl = (window as any).environment.apiBaseUrl;
  treeData;
  menuList: Array<MenuItemModel>;
  defaultKeys;
  expandKeys;
  activedNode: NzTreeNode;

  stadiaCode: string = ''; //  当前测站编码
  stadiaParentCode: string = ''; //  当前测站编码
  stationName: string = '';

  processOpt: any = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        animation: false,
        label: {
          backgroundColor: '#505765'
        }
      }
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: [
      {
        name: 'm³',
        type: 'value'
      }
    ],
    series: [
      {
        name: '补水量',
        type: 'line',
        smooth: true,
        data: []
      },
      {
        name: '累计补水量',
        type: 'line',
        smooth: true,
        data: []
      }
    ]
  };
  processOptChange: any = {};
  //  水位流量日期选择 默认今天
  featureForm: FormGroup;

  /*****************  旬月特征值对比  *********************/
  valTypeOptions = [
    {label: '合计', value: '1'},
    {label: '最大值', value: '2'},
    {label: '最小值', value: '3'},
  ];

  valType = '1';
  dateTypeOptions = [{label: '月', value: '1'}, {label: '旬', value: '2'}];
  dateType = '1';
  curYear: string = '2020';
  year1: Date = new Date('2018');
  year2: Date = new Date('2019');
  monthData: any = {};
  monthOpt: any = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    legend: {
      data: [],
      bottom: 0
    },
    grid: {
      top: '10%',
      bottom: '8%',
      left: '6%',
      right: '4%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      name: 'm³',
      type: 'value'
    },
    series: []
  };
  monthOptChange: any = {};
  /******************* end *******************/

  /******************* 监测数据 *******************/
  tableData = [];
  pageNum = 1;
  pageSize = 10;
  /******************* end *******************/


  /******************* 历史同期对比 *******************/
  hType = 'val';
  historyTypes = [{label: '补水量', value: 'val'}, {label: '累计补水量', value: 'valTotal'}];
  historyYear1: Date = new Date('2017');
  historyYear2: Date = new Date('2020');
  historyRangeValue = [startOfMonth(new Date()), endOfMonth(new Date())];
  historyLists: any[] = [];
  historyOpt: any = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    legend: {
      data: [this.historyYear1, this.historyYear2]
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: this.historyYear1,
        type: 'line',
        data: []
      },
      {
        name: this.historyYear2,
        type: 'line',
        data: []
      }
    ]
  };
  historyOptChange: any = {};

  /******************* end *******************/
  constructor(private fetchService: FetchService,
              private mapService: OneMapService,
              private message: NzMessageService,
              private http: HttpClient,
              private fb: FormBuilder) {
    this.featureForm = this.fb.group({
      maxVal: [''],
      minVal: [''],
      maxTime: [''],
      minTime: [''],
      avgVal: [''],
      medianVal: [''],
      last3AvgVal: [''],
      last3MedianVal: [''],
      compareWarning: [''],
      compareSecure: [''],
    });
  }

  ngOnInit() {
    this.fetchService.post<any>('sys/sysApiInfo/queryApiData', {apicode: 21}).subscribe(res => {
      const treeList = [...[{id: '0', pid: null, name: 'root'}], ...res];
      this.treeData = this.formatToCascadeData(treeList, '0');
      this.getTreeData(this.treeData);
      this.treeData = this.treeData[0].children;
      this.expandKeys = [this.treeData[0].key];
      this.defaultKeys = [this.treeData[0].children[0].key];
      this.checkDetail(this.treeData[0].children[0]);
    });
  }

  checkDetail(e): void {
    const node = e.node ? e.node.origin : e;
    if (node.isLeaf) {
      this.activedNode = e.node || e;
      this.stationName = node.title;
      this.stadiaCode = node.key;
      this.stadiaParentCode = node.pid;
      this.queryInfo();
    }

  }

  queryInfo(): void {
    if (this.stadiaCode && !this.stadiaCode.includes('m')) {
      this.onQueryProcessList();
      this.onQueryMonthList();
      this.onQueryHistory();
    }
  }

  onQueryProcessList() {
    const url = 'report/ecology/data';
    const params = {
      frId: this.stadiaParentCode.replace(/m/, ''),
      lwId: this.stadiaCode,
      stDate: format(this.dateRangeVal[0], 'YYYY-MM-DD'),
      edDate: format(this.dateRangeVal[1], 'YYYY-MM-DD')
    };
    this.fetchService.post<any>(url, params).subscribe(res => {
      this.featureForm.patchValue(res);
      this.tableData = res['originalDataList'];
      const commonOpt = {
        legend: {
          data: ['补水量', '累计补水量'],
          bottom: 10
        },
        xAxis: {
          data: this.getItemValues(this.tableData, 'time')
        }
      };
      this.processOptChange = {
        ...commonOpt, ...{
          series: [
            {
              name: '补水量',
              type: 'line',
              itemStyle: {
                normal: {
                  color: '#289df5', // 折线条的颜色
                  borderColor: '#289df5', // 拐点边框颜色
                  areaStyle: {
                    type: 'default',
                    opacity: 0.1
                  }
                }
              },
              data: this.getItemValues(this.tableData, 'val')
            },
            {
              name: '累计补水量',
              type: 'line',
              itemStyle: {
                normal: {
                  color: '#fbc01b',
                  borderColor: '#fbc01b',
                  areaStyle: {
                    type: 'default',
                    opacity: 0.1
                  }
                }
              },
              data: this.getItemValues(this.tableData, 'valTotal')
            }
          ]
        }
      };
    });
  }

  onQueryMonthList() {
    const url = 'report/ecology/monthXunCampare';
    const params = {
      frId: this.stadiaParentCode.replace(/m/, ''),
      lwId: this.stadiaCode,
      stYear: this.year1.getFullYear(),
      edYear: this.year2.getFullYear(),
      dateType: this.dateType,
      valType: this.valType
    };
    this.fetchService.post<any>(url, params).subscribe((data: any) => {
      this.monthData = data;
      this.changeMonthChart();
    });
  }

  changeMonthChart() {
    this.monthOptChange = {
      xAxis: {
        data: this.monthData[0].list.map(item => {
          return item.m + '月';
        })
      },
      legend: {
        data: ['历史', '今年']
      },
      series: [
        {
          name: '历史',
          type: 'bar',
          data: this.monthData[1].list.map(item => {
            return item.val;
          })
        },
        {
          name: '今年',
          type: 'bar',
          data: this.monthData[0].list.map(item => {
            return item.val;
          })
        },
      ]
    };
  }

  onQueryHistory() {
    const url = 'report/ecology/hisCampare';
    const param = {
      frId: this.stadiaParentCode.replace(/m/, ''),
      lwId: this.stadiaCode,
      stDate: format(this.historyRangeValue[0], 'MM-DD'),
      edDate: format(this.historyRangeValue[1], 'MM-DD'),
      years: this.historyYear1.getFullYear() + ',' + this.historyYear2.getFullYear()
    };
    this.fetchService.post<any>(url, param).subscribe(res => {
      console.log(res);
      this.changeHistoryChart(res);
    });
  }

  changeHistoryChart(lists) {

    const tempList = lists[0].list.length > 0 ? lists[0] : lists[1];
    const xAxisData = tempList.list.map(item => {
      return item.time.substr(5);
    });
    const legendData: any[] = [];
    const seriesData: any[] = [];
    const itemStyles = [
      {
        normal: {
          color: '#289df5', // 折线条的颜色
          borderColor: '#289df5', // 拐点边框颜色
          areaStyle: {
            type: 'default',
            opacity: 0.1
          }
        }
      },
      {
        normal: {
          color: '#fbc01b',
          borderColor: '#fbc01b',
          areaStyle: {
            type: 'default',
            opacity: 0.1
          }
        }
      },
    ];
    lists.map((line, index) => {
      legendData.push(line.year);
      seriesData.push({
        name: line.year,
        type: 'line',
        smooth: true,
        itemStyle: itemStyles[index % 2],
        data: line.list.map(item => {
          return item[this.hType];
        })
      });
    });
    this.historyOptChange = {
      legend: {
        data: legendData
      },
      xAxis: {
        data: xAxisData
      },
      series: seriesData
    };
    console.log(this.historyOptChange);
  }

  private getItemValues(list, key) {
    return list.map(i => {
      return i[key] || 0;
    });
  }

  private formatToCascadeData(data, rootId): any {
    const formatArr = [];
    for (const item of data) {
      const obj = {
        id: item.id,
        name: item.name,
        pid: item.pid,
        children: []
      };
      formatArr.push(obj);
    }
    if (formatArr.length > 1) {
      return this.listToTreeWithLevel(formatArr, null, 0, rootId);
    } else {
      formatArr[0].level = 1;
      return formatArr;
    }
  }

  private listToTreeWithLevel(list, parent, level, rootId?): Array<any> {
    const out = [];
    for (const node of list) {
      if (node.pid === parent) {
        node.level = level;
        const children = this.listToTreeWithLevel(list, node.id, level + 1, rootId);
        if (children.length) {
          node.children = children;
        }
        out.push(node);
      }
    }
    return out;
  }

  getTreeData(data) {
    data.map(item => {
      item.title = item.name;
      item.key = item.id;
      if (item.children && item.children.length) {
        this.getTreeData(item.children);
      } else {
        item.isLeaf = true;
      }
    });
  }

  exportTzz(): void {
    const param = {
      frId: this.stadiaParentCode.replace(/m/, ''),
      lwId: this.stadiaCode,
      stDate: format(this.dateRangeVal[0], 'YYYY-MM-DD'),
      edDate: format(this.dateRangeVal[1], 'YYYY-MM-DD'),
      valType: this.dateType
    };
    this.fetchService.export('report/ecology/expData', param).subscribe((res: any) => {
      const blob = new Blob([res], {type: 'application/vnd.ms-excel    application/x-excel;charset=utf-8'});
      const elink = document.createElement('a');

      elink.download = "生态用水单对象分析_" + new Date().getTime() + ".xls";
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href); // 释放URL 对象
      document.body.removeChild(elink);
    });

    /*this.http
      .post(this.baseUrl + 'report/ecology/expData', param, {
        responseType: 'arraybuffer',
        observe: "response",
        headers: { 'Content-Type': 'application/json' }
      }).subscribe((res: any) => {

      const blob = new Blob([res.body], { type: 'application/vnd.ms-excel    application/x-excel;charset=utf-8' });
      const elink = document.createElement('a');

      elink.download = "download.xls";
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href); // 释放URL 对象
      document.body.removeChild(elink);
    });*/
  }
}
